<template>
  <el-dialog
    title="用户注册"
    :visible.sync="dialogVisible"
    width="600px"
    @close="closed"
  >
    <el-form
      label-position="left"
      :model="form"
      :rules="rules"
      ref="form"
      label-width="100px"
    >
      <el-form-item label="头像" prop="avatar">
        <el-upload
          :data="uploadObj"
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" show-password></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="16"
          ><el-form-item label="图形码" prop="code">
            <el-input v-model="form.code"></el-input> </el-form-item
        ></el-col>
        <el-col :span="6" style="margin-left:10px;height:40px"
          ><img :src="imgCaptcha" @click="getImgCaptcha" alt=""
        /></el-col>
      </el-row>
      <el-row>
        <el-col :span="16"
          ><el-form-item label="验证码" prop="rcode">
            <el-input v-model="form.rcode"></el-input> </el-form-item
        ></el-col>
        <el-col :span="7" style="margin-left:10px;height:40px"
          ><el-button @click="getCaptcha">获取用户验证码</el-button></el-col
        >
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
export default {
  data () {
    return {
      uploadObj: {
        image: ''
      },
      imageUrl: '', //上传头像成功返回的文件
      imgCaptcha: process.env.VUE_APP_BASEURL + '/captcha?type=sendsms',
      dialogVisible: false,
      uploadUrl: process.env.VUE_APP_BASEURL + '/uploads', //头像上传的地址
      form: {
        username: '',
        phone: '',
        email: '',
        avatar: '',
        password: '',
        code: '',
        rcode: ''
      },
      rules: {
        avatar: [{ required: true, message: '头像不能为空', trigger: 'blur' }],
        username: [
          { required: true, message: '昵称不能为空', trigger: 'blur' }
        ],
        email: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('邮箱不能为空'))
                return
              }
              const reg = /^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/
              if (!reg.test(value)) {
                callback(new Error('邮箱不合法'))
                return
              }
              callback() //验证成功也要调用callback
            },
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('手机号不能为空'))
                return
              }
              const reg = /^1[3-9][0-9]{9}$/
              if (!reg.test(value)) {
                callback(new Error('手机号不合法'))
                return
              }
              callback() //验证成功也要调用callback
            },
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 16, message: '密码为6-16位', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '图形码不能为空', trigger: 'blur' },
          { min: 4, max: 4, message: '图形码必须为4位数', trigger: 'blur' }
        ],
        rcode: [
          { required: true, message: '验证码不能为空', trigger: 'blur' },
          { min: 4, max: 4, message: '验证码必须为4位数', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png' || 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      // 给上传头型添加额外参数（这个是后台要求的）, image 属性是接口中规定的
      this.uploadObj.image = file
      return isJPG && isLt2M
    },
    handleAvatarSuccess (res, file) {
      // 判断是否上传成功，成功实现图片预览
      this.imageUrl = URL.createObjectURL(file.raw)
      // 并将图片上传成功后返回的地址赋值给avatar，实现后面的注册功能
      this.form.avatar = res.data.file_path
    },
    getImgCaptcha () {
      this.imgCaptcha =
        process.env.VUE_APP_BASEURL + '/captcha?type=sendsms&t=' + Date.now()
    },
    async getCaptcha () {
      // 校验局部数据
      let num = 0
      this.$refs.form.validateField(['phone', 'code'], res => {
        if (!res) {
          num++
        }
      })
      if (num === 2) {
        let res = await this.$axios.post('/sendsms', {
          code: this.form.code,
          phone: this.form.phone
        })
        if (res.code === 200) {
          //  提示用户获取验证码成功
          this.$message.success('验证码已获取')
          // 将获取的验证码赋值给验证码输入框
          this.form.rcode = res.data.captcha
        } else {
          //  提示用户获取失败
          this.$message.error(res.message)
          // 刷新图片验证码
          this.getImgCaptcha()
        }
      }
    },
    submit () {
      // 全局校验
      this.$refs.form.validate(async valid => {
        if (!valid) return
        // 验证通过发送请求
        let res = await this.$axios.post('/register', this.form)
        if (res.code === 200) {
          // 注册成功提示用户
          this.$message.success('注册成功')
          // 隐藏对话框
          this.dialogVisible = false
        } else {
          // 失败也提示用户
          this.$message.error(res.message)
          // 刷新图形验证码
          this.getImgCaptcha()
        }
      })
    },
    closed () {
      console.log(this.$refs.form)
      this.$refs.form.resetFields()
      // 手动清空头像预览
      this.imageUrl = ''
    }
  }
}
</script>
<style>
.avatar-uploader {
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px !important;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
